<template>
    <div class="table-box">
        <div class="table-toolbar">
            <el-row :gutter="10">
                <el-col :span="1.5">
                    <el-tooltip effect="light" content="保存" placement="top-start">
                        <el-button plain circle size="small" @click="saveFieldHandle">
                            <template #icon>
                                <dbant-icon icon="save"></dbant-icon>
                            </template>
                        </el-button>
                    </el-tooltip>

                </el-col>

                <!-- <el-col :span="1.5">
                    <el-tooltip effect="light" content="添加" placement="top-start">
                        <el-button icon="el-icon-plus" plain circle size="small" @click="inserFieldHandle" />
                    </el-tooltip>
                </el-col>

                <el-col :span="1.5">
                    <el-tooltip effect="light" content="删除" placement="top-start">
                        <el-button icon="el-icon-minus" plain circle size="small" @click="deleteFieldHandle" />
                    </el-tooltip>
                </el-col> -->


            </el-row>
        </div>
        <div class="table-body">
            <dbant-tabs v-bind:value="activeTab" @tab-change="tabChangeHandle">
                <el-tab-pane label="字段" name="filedConfig" :closable="false" class="">
                    <div class="table-body-field">

                        <!-- <vxe-table :data="table.fields" size="mini" border stripe :keep-source="true" height="100%"
                            ref="xTable" class="mytable-scrollbar" :column-config="{ resizable: true }"
                            mouse-config="{area:true}" :row-config="{ isHover: true, isCurrent: true }"
                            :keyboard-config="{ isClip: true, isDel: true }"
                            :edit-config="{ trigger: 'click', mode: 'row', enabled: true }" :scroll-y="{ enabled: tru }"
                            @cell-click="tableDesignCellHandle">
                            <vxe-column type="seq" width="60"></vxe-column>
                            <vxe-column field="name" title="名字" show-header-overflow="title" show-overflow="title"
                                width="200" :edit-render="{ autofocus: '.vxe-input--inner' }">
                                <template #edit="{ row }">
                                    <vxe-input v-model="row.name" type="text" @blur="fieldNameBlurHandle(row)"></vxe-input>
                                </template>
                            </vxe-column>
                            <vxe-column field="type" title="类型" show-header-overflow="title" show-overflow="title"
                                width="120"
                                :edit-render="{ autofocus: '.vxe-input--inner', events: { change: selectChange } }"><template
                                    #edit="{ row }">
                                 
                                    <vxe-select v-model="row.type" filterable @change="fieldTypeChangeHandle(row)"
                                        @focus="fieldTypeChangeHandle(row)">
                                        <vxe-option v-for="item in dataType" :key="item.name" :value="item.name"
                                            :label="item.name"></vxe-option>
                                    </vxe-select>
                                </template></vxe-column>
                            <vxe-column field="size" title="长度" show-header-overflow="title" show-overflow="title"
                                width="120" :edit-render="{ autofocus: '.vxe-input--inner' }"><template #edit="{ row }">
                                    <vxe-input v-model="row.size" type="number"
                                        :max="row.maxSize ? row.maxSize : 10000000000"></vxe-input>
                                </template></vxe-column>
                            <vxe-column field="decimalDigits" title="小数点" show-header-overflow="title" show-overflow="title"
                                width="120" :edit-render="{ autofocus: '.vxe-input--inner' }"><template #edit="{ row }">
                                    <vxe-input v-model="row.decimalDigits" type="number"
                                        :max="row.maxDecimalDigits ? row.maxDecimalDigits : 10000000000"></vxe-input>
                                </template></vxe-column>
                            <vxe-column field="nullable" title="为空" show-header-overflow="title" show-overflow="title"
                                width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
                                <template #default="{ row, rowIndex }">
                                    <el-checkbox v-model="row.nullable"></el-checkbox>
                                </template>
                                <template #edit="{ row }">
                                    <el-checkbox v-model="row.nullable"></el-checkbox>
                                </template></vxe-column>
                            <vxe-column field="primaryKey" title="主键" show-header-overflow="title" show-overflow="title"
                                width="80" :edit-render="{ autofocus: '.vxe-input--inner' }">
                                <template #default="{ row, rowIndex }">
                                    <el-checkbox v-model="row.primaryKey"></el-checkbox>
                                </template>
                                <template #edit="{ row }">
                                    <el-checkbox v-model="row.primaryKey"
                                        @change="primaryKeyChangeHandle(row)"></el-checkbox>
                                </template></vxe-column>
                            <vxe-column field="comment" title="注释" show-header-overflow="title" show-overflow="title"
                                width="300" :edit-render="{ autofocus: '.vxe-input--inner' }"><template #edit="{ row }">
                                    <vxe-input v-model="row.comment" type="text"></vxe-input>
                                </template></vxe-column>
                          
                        </vxe-table>

                        <div class="table-body-field-footer"></div> -->

                        <field-edit v-bind="table" ref="fieldEditorRef"></field-edit>

                    </div>

                </el-tab-pane>
                <el-tab-pane label="索引" name="indexConfig" :closable="false" class="table-body-field">
                    <div class="table-body-field">
                        <index-edit v-bind="table" ref="indexEditorRef"></index-edit>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="外键" name="foreignKeyConfig" :closable="false" class="table-body-field">
                    <el-scrollbar>
                        <foreign-key-edit v-bind="table" ref="foreignKeyEditorRef"></foreign-key-edit>
                    </el-scrollbar>
                </el-tab-pane>
                <el-tab-pane label="触发器" name="triggerConfig" :closable="false" class="table-body-field">
                    <el-scrollbar>
                        <trigger-edit v-bind="table" ref="triggerEditorRef"></trigger-edit>
                    </el-scrollbar>
                </el-tab-pane>
                <el-tab-pane label="其他" name="otherConfig" :closable="false" class="table-body-field">
                    <el-scrollbar>
                        <el-form ref="formRef" :model="form" label-width="80px" :rules="rules">
                            <el-form-item label="数据库名" prop="catalogName">
                                <el-input v-model="form.catalogName" clearable :disabled="props.catalogName"></el-input>
                            </el-form-item>
                            <el-form-item label="字符集">
                                <el-select v-model="form.charset" placeholder="请选择字符集" style="width: 100%;" filterable
                                    @change="charsetChangeHandle" clearable>
                                    <el-option :label="item.name" :value="item.name"
                                        v-for="item in characterSets"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="排序规则">
                                <el-select v-model="form.collation" placeholder="请选择排序规则" style="width: 100%;" clearable
                                    filterable>
                                    <el-option :label="item.name" :value="item.name"
                                        v-for="item in charsetChildrenList"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </el-scrollbar>
                </el-tab-pane>
                <el-tab-pane label="sql预览" name="sqlPreview" :closable="false" class="table-body-field">
                    <el-input v-model="sqlPreviewValue" input-style="height:100%;flex:1" type="textarea" />
                </el-tab-pane>
            </dbant-tabs>

        </div>
        <!-- <div class="other-set-box">
            <el-form ref="rowOtherFormRef" :model="rowData" label-width="80px" size="small">
                <el-form-item :label="item.name" :prop="item.key" v-for="item in rowOtherFormConfigData.other">
                    <el-select v-model="rowData[item.key]" clearable filterable v-if="item.type === 'select'" @change="updateRowEditState">
                        <el-option v-for="eo in item.data(rowData)" :key="eo.value" :label="eo.name" :value="eo.value" />
                    </el-select>
                    <el-checkbox v-model="rowData[item.key]" clearable v-if="item.type === 'checkbox'" @change="updateRowEditState" />
                    <el-input v-model="rowData[item.key]" clearable v-if="item.type === 'input'" />
                    <el-input-number v-model="rowData[item.key]" controls-position="right" :min="0"
                        v-if="item.type === 'number'"></el-input-number>
                </el-form-item>
            </el-form>
        </div> -->
        <el-dialog title="保存" v-model="tableNameDialogVisible" width="400px" append-to-body :before-close="handleClose"
            v-if="tableNameDialogVisible">
            <el-form ref="tableFormRef" :model="table" :rules="tableFormRules" label-width="80px">
                <el-form-item label="表名" prop="name">
                    <el-input v-model="table.name" clearable />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="tableNameDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveTableInfoHandle">确 定</el-button>
            </template>


        </el-dialog>

        <!-- <el-dialog title="其他配置" v-model="rowOtherDialogVisible" width="400px" append-to-body :before-close="handleClose"
            v-if="rowOtherDialogVisible">
            <el-form ref="rowOtherFormRef" :model="rowData" label-width="80px" size="small">
                <el-form-item :label="item.name" :prop="item.key" v-for="item in rowOtherFormConfigData.other">
                    <el-select v-model="item.key"   clearable size="small"
                        v-if="item.type === 'select'">
                        <el-option v-for="eo in item.data" :key="eo.value" :label="eo.name" :value="eo.value" />
                    </el-select>
                    <el-checkbox v-model="item.key" clearable v-if="item.type === 'checkbox'"  size="small"/>
                    <el-input v-model="item.key" clearable v-if="item.type === 'input'" size="small" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="table.name = ''; rowOtherDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveTableInfoHandle">确 定</el-button>
            </template>


        </el-dialog> -->
    </div>
</template>

<script setup>
import { ref, defineProps, nextTick, inject, toRefs, reactive, watch, computed, h, defineExpose } from "vue"
import { dataType } from "../service/constant"
import { SqlBuilder } from '../service/SqlBuilder'
import fieldEdit from "./table/fieldEdit.vue"
import indexEdit from "./table/indexEdit.vue"
import foreignKeyEdit from "./table/foreignKeyEdit.vue"
import triggerEdit from "./table/triggerEdit.vue"
const props = defineProps({
    connId: {
        type: [String, Number],
        required: true,
        default: undefined
    },
    catalog: {
        type: String,
        default: undefined
    },
    tableName: {
        type: String,
        default: undefined
    }
});
const $sqlFormat = inject("$sqlFormat")
const $request = inject('$request');
const $message = inject('$message');
const $bus = inject("$bus")
const $config = inject("$config")
const fieldEditorRef = ref(null);
const indexEditorRef = ref(null)
const foreignKeyEditorRef = ref(null)
const triggerEditorRef = ref(null)
const sqlBuilder = new SqlBuilder();
const activeTab = ref("filedConfig")
const table = ref({
    connId: props.connId,
    catalogName: props.catalog,
    name: props.tableName,
    fields: [],
    indexs: []
})
const sqlPreviewValue = ref('');

const tableFormRef = ref(null)
const tableFormRules = {
    name: [
        { required: true, message: '请输入数据库名', trigger: 'blur' },
    ]
}
const form = ref({})

const createState = ref(!props.tableName);

const tableNameDialogVisible = ref(false)
const updateFieldData = ref([]);
const saveFieldHandle = () => {

    if (createState.value) {
        tableNameDialogVisible.value = true;
        return;
    }
    buildSql();
    if (!sqlPreviewValue.value) {
        return;
    }
    const executeParams = { script: sqlPreviewValue.value };
    const params = { connId: props.connId, catalog: props.catalog, executeParams: executeParams };
    $request.post(`/sqlDatabase/executeScript`, params)
        .then((res) => {
            //没有数据就设置空数据
            if (!res.data) {
                return;
            }
            
            const failResult = res.data.filter(item => !item.success)
            if (failResult.length == 0) {
                $message.success('保存成功');
                clearEditStateHandle();
            } else {
                $message.error(failResult[0].message);
            }

        })

}


const clearEditStateHandle = () => {
    sqlPreviewValue.value = "";
    reload();
    tableNameDialogVisible.value = false
    updateFieldData.value = [];
    createState.value = false;
    //刷新列表
    $bus.$emit($config.REFRESH_PARENT_NODE)
}




const saveTableInfoHandle = async () => {
    await tableFormRef.value.validate(async (valid) => {
        if (valid) {

            buildSql();
            if (!sqlPreviewValue.value) {
                return;
            }
            const executeParams = { script: sqlPreviewValue.value };
            const params = { connId: props.connId, catalog: props.catalog, executeParams: executeParams };
            $request.post(`/sqlDatabase/executeScript`, params)
                .then((res) => {
                    //没有数据就设置空数据
                    if (!res.data) {
                        return;
                    }
                    
                    const failResult = res.data.filter(item => !item.success)
                    if (failResult.length == 0) {
                        $message.success('保存成功');
                        clearEditStateHandle();
                    } else {
                        $message.error(failResult[0].message);
                    }
                })
             
        }
    })
}








const tabChangeHandle = (tabName) => {
    if (tabName === 'sqlPreview') {
        try {
            buildSql();
        } catch (e) {
            console.error(e);
        }

    }
}



/**
 * 构建sql语句
 */

const buildSql = () => {
    let data = {
        name: table.value.name,
        catalogName: table.value.catalogName,
        fields: fieldEditorRef.value.getChangeData(),
        indexs: indexEditorRef.value.getChangeData(),
        foreignKeys: foreignKeyEditorRef.value.getChangeData(),
        triggers: triggerEditorRef.value.getChangeData()
    }
    if (createState.value) {
        sqlPreviewValue.value = sqlBuilder.createTable(data);
    } else {
        data = {
            name: table.value.name,
            catalogName: table.value.catalogName,
            fields: fieldEditorRef.value.getChangeData(),
            indexs: indexEditorRef.value.getChangeData(),
            foreignKeys: foreignKeyEditorRef.value.getChangeData(),
            triggers: triggerEditorRef.value.getChangeData()
        }
        sqlPreviewValue.value = sqlBuilder.alterTable(fieldEditorRef.value.getFullFields(), data)
    }
    if (sqlPreviewValue.value) {
        try{
            sqlPreviewValue.value = $sqlFormat(sqlPreviewValue.value)
        }catch(e){
            console.log(e)
        }
      
    }

}





const init = () => {


}
init();
//重新刷新组件
const reload = () => {
    init();
    fieldEditorRef.value.reload();
    indexEditorRef.value.reload();
    foreignKeyEditorRef.value.reload();
    triggerEditorRef.value.reload()
}
//设置可访问参数和方法
defineExpose({ reload })
</script>

<style lang="scss" scoped>
.table-box {
    display: flex;
    flex-direction: column;
    height: 100%;

    :deep(.el-tabs-box) {
        height: 100%;


    }

    :deep(.el-tabs) {
        height: 100%;
    }

    .table-toolbar {
        padding: 0px 5px 5px 5px;
    }

    .table-body {

        flex: 1;
        height: 100%;

        display: flex;
        flex-direction: column;

        .table-body-field {
            height: calc(100vh - 350px);
            flex: 1;
        }

        .table-body-field-footer {
            height: 30px;
        }

    }

    .other-set-box {
        height: 200px;
        background: #fff;
        border-top: 1px solid #cdcdcd;
        padding: 10px;
    }
}

/*滚动条整体部分*/
.mytable-scrollbar ::-webkit-scrollbar {
    width: 12px;
    height: 12px;
}

/*滚动条的轨道*/
.mytable-scrollbar ::-webkit-scrollbar-track {
    background-color: #FFFFFF;
}

/*滚动条里面的小方块，能向上向下移动*/
.mytable-scrollbar ::-webkit-scrollbar-thumb {
    background-color: #bfbfbf;
    border-radius: 5px;
    border: 1px solid #F1F1F1;
    box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
}

.mytable-scrollbar ::-webkit-scrollbar-thumb:hover {
    background-color: #A8A8A8;
}

.mytable-scrollbar ::-webkit-scrollbar-thumb:active {
    background-color: #787878;
}

/*边角，即两个滚动条的交汇处*/
.mytable-scrollbar ::-webkit-scrollbar-corner {
    background-color: #FFFFFF;
}

.vxe-dropdown--panel {
    z-index: 2010 !important
}

//日期框
.vxe-input--panel.type--date,
.vxe-input--panel.type--month,
.vxe-input--panel.type-- week,
.vxe-input--panel.type--year {
    z-index: 9998 !important
}

//选择框
.vxe-select--panel {
    z-index: 9997 !important
}
</style>